package com.htwz.admin.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.htwz.admin.api.dto.LoginBody;
import com.htwz.admin.api.entity.SysUser;
import com.htwz.admin.service.LoginService;
import com.htwz.admin.service.SysUserService;
import com.htwz.common.core.constant.enums.DeviceType;
import com.htwz.common.core.dto.LoginUser;
import com.htwz.common.core.exception.ErrorCodes;
import com.htwz.common.core.util.MsgUtils;
import com.htwz.common.core.util.R;
import com.htwz.common.satoken.utils.LoginHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

	private final SysUserService userService;

	public R login(LoginBody loginBody) {
		SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, loginBody.getUsername()).or()
				.eq(SysUser::getPhone, loginBody.getUsername()));
		if (user == null) {
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, loginBody.getUsername()));
		}
		LoginUser userInfo =  userService.getUserInfo(user);
		if (!BCrypt.checkpw(loginBody.getPassword(), userInfo.getPassword())) {
			return R.failed("密码错误");
		}
		// 获取登录token
		LoginHelper.loginByDevice(userInfo, DeviceType.PC);
		return R.ok(StpUtil.getTokenValue());
	}

	public R<String> smsLogin(String mobile) {
		SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, mobile));
		LoginUser userInfo =  userService.getUserInfo(user);
		// 获取登录token
		LoginHelper.loginByDevice(userInfo, DeviceType.PC);
		return R.ok(StpUtil.getTokenValue());
	}

}
